'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
    // event为客户端上传的参数
    console.log('event : ', event);
    
    const collection = db.collection('uni-id-users');
    
    // 如果是注册操作
    if (event.action === 'register') {
        // 检查用户名是否已存在
        let existingUser = await collection.where({
            username: event.username
        }).get();
        
		console.log(event);
        if (existingUser.data.length > 0) {
            return {
                code: -1,
                msg: '用户名已存在'
            };
        }
        
        // 创建新用户
        let newUser = await collection.add({
            username: event.username,
            password: event.password
        });
        
        return {
            code: 0,
            msg: '注册成功'
        };
    }
    
    // 如果是登录操作
    if (event.action === 'login') {
        let user = await collection.where({
            username: event.username,
            password: event.password
        }).get();
        
        // 判断查询结果是否为空数组
        if (user.data.length < 1) {
            return {
                code: -1,
                msg: '用户名或密码错误'
            };
        } else {
            return {
                code: 0,
                msg: '登录成功'
            };
        }
    }
    
    // 返回数据给客户端
    return event;
};
